

const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
//获取年月日
const formatTimeSecond = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return [year, month, day].map(formatNumber).join('-')
}
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
// 获取小时分钟秒
const formatTodayTime = date => {
    const hour = date.getHours()
    const minute = date.getMinutes()
    return [hour, minute].map(formatNumber).join(':')
}
// 当前时间加10分钟 用于待支付的截至时间
const formatTimes = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate() + 30
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
//时间戳转换成日期时间
function timestampChangedate(unixtime) {
    var date = new Date(unixtime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    // return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;//年月日时分秒
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
}
// 根据时间戳转换天 时 分 秒
function formatSeconds(value) {
    var theTime = parseInt(value); // 需要转换的时间秒 
    var theTime1 = 0; // 分 
    var theTime2 = 0; // 小时 
    var theTime3 = 0; // 天
    if (theTime > 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
            if (theTime2 > 24) {
                //大于24小时
                theTime3 = parseInt(theTime2 / 24);
                theTime2 = parseInt(theTime2 % 24);
            }
        }
    }
    var result = '';
    if (theTime >= 0) {
        var a = parseInt(theTime) + "";
        if (a.lngth === 1) {
            result = "" + a + "0秒";
        } else {
            result = "" + a + "秒";
        }
    }
    if (theTime1 > 0) {
        result = "" + parseInt(theTime1) + "分" + result;
    }
    if (theTime2 > 0) {
        result = "" + parseInt(theTime2) + "小时" + result;
    }
    if (theTime3 > 0) {
        result = "" + parseInt(theTime3) + "天" + result;
    }
    return result;
}

/**
 * 计算导航栏的高度
 * 计算状态栏与导航栏的总高度
 * const statusNavBarHeight = statusBarHeight + navBarHeight;
 */
function navBarHeight() {
    // 获取状态栏高度
    const {
        statusBarHeight
    } = wx.getSystemInfoSync();
    // 得到右上角菜单的位置尺寸 px
    const menuButtonObject = wx.getMenuButtonBoundingClientRect();
    const {
        top,
        height
    } = menuButtonObject;
    // 计算导航栏的高度 = 此高度基于右上角菜单在导航栏位置垂直居中计算得到
    return height + (top - statusBarHeight) * 2;
}



/**
 * 检查微信会话是否过期
 */
function checkSession() {
    return new Promise(function (resolve, reject) {
        wx.checkSession({
            success: function () {
                resolve(true);
            },
            fail: function () {
                reject(false);
            }
        })
    });
}
/**
 * 判断页面是否需要登录
 */
function redirect(url) {
    if (false) {} else {
        wx.redirectTo({
            url: url
        });
    }
}

function showErrorToast(msg) {
    wx.showToast({
        title: msg,
        image: '/static/images/icon_error.png'
    })
}

function showSuccessToast(msg) {
    wx.showToast({
        title: msg,
    })
}

// 获取当前页面url及参数
function getCurrentPageUrlWithArgs() {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = currentPage.route
    const options = currentPage.options
    let urlWithArgs = `/${url}?`
    for (let key in options) {
        const value = options[key]
        urlWithArgs += `${key}=${value}&`
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
    return urlWithArgs
}

/* js小数乘法
 *@parameter arg1：被乘数（接受小数和整数）
 *@parameter arg2：乘数（接受小数和整数）
 *@parameter fix: 乘积保留几位（接受正负整数以及0）
 */
function accMul(arg1, arg2 = 0.01, fix = 2) {
    if (!parseInt(fix) == fix) {
        return;
    }
    var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length
    } catch (e) {}
    try {
        m += s2.split(".")[1].length
    } catch (e) {}
    if (m > fix) {
        return (Math.round(Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m - fix)) / Math.pow(10, fix));
    } else if (m <= fix) {
        return (Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)).toFixed(fix);
    } else {
        return (arg1 * arg2).toFixed(fix).toString();
    }
}
/* 
* 金额转换
* 使用方式
* var data=util.unitConvert(12311111);
   console.log(data.num+data.unit) //10.00万元
*/
function unitConvert(num) {
    var moneyUnits = ["元", "万", "亿", "万亿"]
    var dividend = 10000;
    var curentNum = num;
    //转换数字
    var curentUnit = moneyUnits[0];
    //转换单位
    for (var i = 0; i < 4; i++) {
        curentUnit = moneyUnits[i]
        if (strNumSize(curentNum) < 5) {
            break;
        }
        curentNum = curentNum / dividend
    }
    var m = {
        num: 0,
        unit: ""
    } // 定义返回的对象
    m.num = curentNum;
    m.unit = curentUnit;
    return m;
}
// 获取数字字符串长度
function strNumSize(tempNum) {
    var stringNum = tempNum.toString()
    var index = stringNum.indexOf(".")
    var newNum = stringNum;
    if (index != -1) {
        newNum = stringNum.substring(0, index)
    }
    return newNum.length
}


// json 转 Param
function JSON2Params(data) {
    try {
        var tempArr = [];
        for (var i in data) {
            var key = encodeURIComponent(i);
            var value = encodeURIComponent(data[i]);
            tempArr.push(key + '=' + value);
        }
        var urlParamsStr = tempArr.join('&');
        return urlParamsStr;
    } catch (err) {
        return '';
    }
}
// 防抖
function debounce(fn, interval) {
    var timer;
    var gapTime = interval || 1000; //间隔时间 不传值默认为1000ms
    return function () {
        clearTimeout(timer);
        var that = this;
        var args = arguments; //保存arguments setTimeout是全局的 arguments不是防抖函数需要的
        timer = setTimeout(function () {
            fn.call(that, args);
        }, gapTime);
    };
}

// uuid


function wxuuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
        i;
    radix = radix || chars.length;

    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        // rfc4122, version 4 form
        var r;

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}


function parseTime (time, cFormat) {
    if (arguments.length === 0) {
      return null
    }
    const format = cFormat || '{y}-{m}-{d}'
    let date
    if (typeof time === 'undefined' || time === null || time === 'null') {
      return ''
    } else if (typeof time === 'object') {
      date = time
    } else {
      if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
        time = parseInt(time)
      }
      if ((typeof time === 'number') && (time.toString().length === 10)) {
        time = time * 1000
      }
      date = new Date(time)
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key]
      // Note: getDay() returns 0 on Sunday
      if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return time_str
  }

module.exports = {
    formatTimeSecond,
    formatTime,
    formatTimes,
    formatTodayTime,
    timestampChangedate,
    formatSeconds,
    navBarHeight,
    redirect,
    showErrorToast,
    showSuccessToast,
    checkSession,
    getCurrentPageUrlWithArgs,
    accMul,
    unitConvert,
    JSON2Params,
    debounce,
    wxuuid,
    parseTime
}